package br.com.sga.controlador;

import br.com.sga.erro.GeralException;
import br.com.sga.modelo.regra.RUsuarioValida;
import br.com.sga.modelo.regra.Regra;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author kenzo
 */
public class UserValidationFilter implements Filter {
    private Regra validacao;

    public UserValidationFilter(){
        //
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain)throws IOException, ServletException {
        String destino = "error";
        try {
            destino = validacao.executar((HttpServletRequest)request);
            if(destino!=null)
                ((HttpServletRequest)request).getRequestDispatcher(destino).forward(request, response);
            else
                chain.doFilter(request, response);
                
        } catch (GeralException e) {
            request.setAttribute("erro",e);
            ((HttpServletRequest)request).getRequestDispatcher(destino).forward(request, response);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {        
        validacao = new RUsuarioValida();
    }

    @Override
    public void destroy() {
        //
    }
    
}
